//
// Created by francklinson on 2021/10/21 AT 14:24.
//
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
#include <functional>
#include <climits>
#include <string>

using namespace std;

class Solution {
public:
    int countKDifference(vector<int> &nums, int k) {
        int n = nums.size();
        int ans = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (abs(nums[i] - nums[j]) == k)
                    ++ans;
            }
        }
        return ans;
    }

    int countKDifference2(vector<int> &nums, int k) {
        unordered_map<int, int> mp;
        // hash统计各个数字的个数
        for (int num: nums)
            ++mp[num];
        int ans = 0;
        for (auto x: mp) {
            // 如果存在x和x+k  那么结果增加它们个数的乘积
            auto it = mp.find(x.first + k);
            if (it != mp.end()) {
                ans += it->second * x.second;
            }
        }
        return ans;
    }
};

int main() {
    vector<int> nums{1, 2, 2, 1};
    Solution solution;
    cout << solution.countKDifference2(nums, 1) << endl;
    return 0;
}

